<?php
namespace Modules\Activity\Http\Controllers\Client\Lottery;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Lottery\Activity;
use \Modules\Activity\Entities\Lottery\Record;
// use \Modules\User\Entities\User;

use Validator;
use ThrowException;
use Auth;
use DB;

// 参与活动的用户（is_lucker_user）
class UserController extends Controller
{
    // 用户列表
    public function index(Request $req, $uuid)
    {
        $rule = [
            'type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        // $options = $req->all();

        $activity = Activity::getEntity([
            'uuid' => $uuid
        ]);

        if ($req->type === 'lucky') {
            $builder =  $activity->records()->lucky(); 
        }
        elseif ($req->type === 'all') {
            $builder =  $activity->records(); 
        }

        // 只获取当期用户
        $session = $req->input('session', 'all');
        if ($session === 'current') {
            $builder->where('session', $activity->current_session);
        }

        $list = Record::getList([
            'per_page' => $req->input('per_page', 12),
            'builder' => $builder,
            'with' => ['user'],
            'with_count' => ['tickets'],
            'only' => [
                'id',
                'tickets_count',
                'session',
                'user' => [
                    'name',
                    'headimg',
                ]
            ]
        ]);

        return $list->generateListResponse();
    }


    public function luckyUserIndex(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $activity = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $builder =  $activity->records()->lucky(); 

        // 只获取当期用户
        $session = $req->input('session', 'all');
        if ($session === 'current') {
            $builder->where('session', $activity->current_session);
        }

        $list = Record::getList([
            'builder' => $builder,
            'with' => ['user'],
            // 'with_count' => ['lottery_tickets', 'invitees'],
            'only' => [
                'id',
                'lottery_tickets_count',
                'invitees_count',
                'is_lucky_user',
                'created_at',
                'session',
                'lucky_ticket' => [
                    'sku',
                    'number',
                    'is_picked'
                ],
                'user' => [
                    'name',
                    'headimg',
                    'gender'
                ]
            ]
        ]);

        $list->each(function ($item) {
            $item->lucky_ticket = $item->tickets()->lucky()->first();
        });

        return $list->generateListResponse();
    }
}
